﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CapturePackage.Utility
{
    public class HttpHelper
    {
        /// <summary>
        /// 根据url下载内容  之前是GB2312
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string DownloadUrl(string url)
        {
            return DownloadHtml(url, Encoding.UTF8);
        }

        public static string DownloadElm(string url)
        {
            return DownloadElmHtml(url, Encoding.UTF8);
        }

        /// <summary>
        /// 下载html
        /// http://tool.sufeinet.com/HttpHelper.aspx
        /// HttpWebRequest功能比较丰富，WebClient使用比较简单
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string DownloadElmHtml(string url, Encoding encode)
        {
            string html = string.Empty;
            try
            {
                //https可以下载--
                //设置https等级
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) =>
                //{
                //    return true; //总是接受  
                //});
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                {
                    //url = "https://h5.ele.me/minisite/?spm=a2ogi.13147251.0.0";
                    //HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;//模拟请求
                    //request.Timeout = 30 * 1000;//设置30s的超时
                    //request.Method = "Get";
                    ////设置用户请求的身份 设置的为浏览器

                    //request.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1";
                    ////request.UserAgent = "User - Agent:Mozilla / 5.0(iPhone; CPU iPhone OS 7_1_2 like Mac OS X) App leWebKit/ 537.51.2(KHTML, like Gecko) Version / 7.0 Mobile / 11D257 Safari / 9537.53";

                    //request.ContentType = "text/plain;charset=UTF-8";// "text/html;charset=gbk";// 
                    //                                                 //request.Host = "search.yhd.com"
                    //request.Referer = "https://h5.ele.me/minisite/?spm=a2ogi.13162730.zebra-ele-login-module-9089118186&latitude=30.266943&longitude=120.110139&__locPid=B023B07KQU&__locAid=717318666198801&__locAt=5&__locFrom=h5";
                    //request.Headers.Add("Cookie", @"cna=eIRoHix2eSQBASQOA5B6Ls2Z; ubt_ssid=m8b32j0g6ho96l53b3olfduikftay5s6_2024-10-18; perf_ssid=cd5ypuys5fflomj9tjlyfpo7k76q8usa_2024-10-18; _bl_uid=hRmXU2t4eCbj8O6gvl3gyga1RXk7; t=47a13eae06088c3ed0a7ef647a685cc1; munb=2205181437154; unb=2205181437154; USERID=1946207929; UTUSER=1946207929; ucn=eleme_zb; from=mobile.default; __itrace_wid=4cc2cdc2-7530-4192-3a35-a17577ca5f67; x5check_ele=afmAHpVw6TYrF9YpSgI4Ut%2F%2FiqL8KOsos7HKhl6v344%3D; xlly_s=1; mtop_partitioned_detect=1; _m_h5_tk=cce89f8d2a552021030ca124acafb768_1729657546370; _m_h5_tk_enc=cfd12f57b98d1aeb067072b30f11977a; _samesite_flag_=true; cookie2=2bec8cffdb9ec38e7868249087c65a6ee; _tb_token_=ee65314ff758e; sgcookie=E100%2FXqAXfend3DF0WEavm1VYwWXL5CDKasvfejkPvhlOSlAIc2vtmo4xkH9GgEaJbD9Vo%2BBm12jL01PlQzZf%2BId77xMMFjZZIaJNqbUr1MrNiY%3D; SID=MmJlYzhjZmZkYjllYzM4ZTc4NjgyNDkwODdjNjVhNmVlli_-mwzj_wnXi1ZfXij1nQ==; app_cityid=2; tfstk=fZ8XPGDwV-2bN0R5IihPAzC-Ua_61KgUh519tCU46ZQY1zBWdN-26Iz6FLJfbIW201U1eZIM0OWVCNOMdbkE82RDiNbxLvuUb0n4DNXt7NpdQupAWvkE8uPRmx793Rg0mnRRE11OMrpTwb1CONUAXrE8eTfOWOpTk83R11eTXNLoVV1oq9AjZBYGY6VCYIB75QT5MiZDMTaTWUt5c9UNFPU9PsOPThfuRcWpxtSFHL3zlNOR1LsecvaXCCdHXgT_HjJpeh9OZ3D_f9t9gHYP45hdpEAJ-aIrJXOJrKRDPCPtW_JFeIYA52hhlZBAP_YZErB62hLVmN2xCOYWwEK14WaFdL2TflXY5_6ENbZgbDgLXGoaAullD_fy3bG7bKsAZ_6ENbZgjiClaKlSNlJf.; isg=BOTkWMm3X08lzauJiUdJUNhWteLWfQjnRxpxH_4FcK9yqYRzJo3YdxoLbQexcUA_");

                    ////request.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                    ////request.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
                    ////request.Headers.Add("Referer", "http://list.yhd.com/c0-0/b/a-s1-v0-p1-price-d0-f0-m1-rt0-pid-mid0-kiphone/");

                    ////Encoding enc = Encoding.GetEncoding("GB2312"); // 如果是乱码就改成 utf-8 / GB2312

                    ////如何自动读取cookie
                    //request.CookieContainer = new CookieContainer();//1 给请求准备个container
                    //using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)//发起请求
                    //{
                    //    if (response.StatusCode != HttpStatusCode.OK)
                    //    {
                    //    }
                    //    else
                    //    {
                    //        try
                    //        {
                    //            //string sessionValue = response.Cookies["ASP.NET_SessionId"].Value;//2 读取cookie
                    //            var xw = response.Cookies;
                    //            StreamReader sr = new StreamReader(response.GetResponseStream());
                    //            html = sr.ReadToEnd();//读取数据
                    //            sr.Close();
                    //        }
                    //        catch (Exception ex)
                    //        {
                    //            html = null;
                    //        }
                    //    }
                    //}
                }

                {
                    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                    TimeSpan timeSpan = DateTime.UtcNow - epoch;
                    long timestamp = (long)timeSpan.TotalMilliseconds;
                    string myString = $@"d085629009e640f3e6990738cbdc96e1&{timestamp}&12574478&{File.ReadAllText("TextFile1.txt")}";
                    MD5 md5 = new MD5CryptoServiceProvider();
                    //byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
                    byte[] fromData = System.Text.Encoding.UTF8.GetBytes(myString);//
                    byte[] targetData = md5.ComputeHash(fromData);
                    string byte2String = null;
                    for (int i = 0; i < targetData.Length; i++)
                    {
                        //这个是很常见的错误，你字节转换成字符串的时候要保证是2位宽度啊，某个字节为0转换成字符串的时候必须是00的，否则就会丢失位数啊。不仅是0，1～9也一样。
                        //byte2String += targetData[i].ToString("x");//这个会丢失
                        byte2String = byte2String + targetData[i].ToString("x2");
                    }
                    string str = byte2String;

                    h5RequestModel h5RequestModel = new h5RequestModel()
                    {
                        jsv = "2.7.2",
                        appKey = "12574478",
                        t = timestamp,
                        sign = str,
                        api = "mtop.relationrecommend.TinyAppRecommend.recommend",
                        v = "1.0",
                        type = "originaljson",
                        dataType = "json",
                        timeout = "10000",
                        mainDomain = "ele.me",
                        subDomain = "waimai-guide",
                        H5Request = "true",
                        ttid = "h5@safari_ios_604.1",
                        SV = "5.0",
                        pageDomain = "ele.me",
                        data = File.ReadAllText("TextFile1.txt"),
                        bx_et = "fy2iM3ZXh5lsUnxASJD1ig9jJIfLdFMjlrpxkx3VT2uQkCrVfivm-yVt7lFTitq4rGiA5-UngzEX6x3YnW90VowOfxIsClMj3aQRe-q_fxt4u58GvH-UA0iVOGHJ5lMj3aKp3_BufzlZWT5i3MDEmmpq3qzqTpoj8do2Qm8FxmgEuxuZbk8EDcRwgVk2z5jr58euLN_L0_iSd6ojjf0DU29Dhinns4rZOaWaKLGizluH3aNIMAgmR87dtkag_PnQoTbnU7a3nbkcIUigTuDEWY5ktAqL58DaENvtvvgtaDyPDQgLKVU4IXSJEjHUebka96_tMAmuuRaMmKzzvuesO-bk8qNtVvo0hgRmojSrgBRyBiJjy9qXGIGZAD0S0O9dF0Zw3lIhxQ7I_DiFuMjHGIGZAD0RxMAPRfoIYZ5.."
                    };
                    string xo = $@"jsv={h5RequestModel.jsv}&appKey={h5RequestModel.appKey}&t={h5RequestModel.t}&sign={h5RequestModel.sign}&api={h5RequestModel.api}&v={h5RequestModel.v}&type={h5RequestModel.type}&dataType={h5RequestModel.dataType}&timeout={h5RequestModel.timeout}&mainDomain={h5RequestModel.mainDomain}&subDomain={h5RequestModel.subDomain}&H5Request={h5RequestModel.H5Request}&ttid={h5RequestModel.ttid}&SV={h5RequestModel.SV}&pageDomain={h5RequestModel.pageDomain}&data={h5RequestModel.data}&ttid={h5RequestModel.ttid}&bx_et={h5RequestModel.bx_et}";
                    url = "https://waimai-guide.ele.me/h5/mtop.relationrecommend.tinyapprecommend.recommend/1.0/5.0/";
       
                    HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;//模拟请求
                    request.Timeout = 30 * 1000;//设置30s的超时
                    request.Method = "POST";
                    //设置用户请求的身份 设置的为浏览器

                    request.Referer = "https://h5.ele.me/";
                    request.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1";
                    //request.UserAgent = "User - Agent:Mozilla / 5.0(iPhone; CPU iPhone OS 7_1_2 like Mac OS X) App leWebKit/ 537.51.2(KHTML, like Gecko) Version / 7.0 Mobile / 11D257 Safari / 9537.53";

                    request.ContentType = "application/x-www-form-urlencoded";// "text/html;charset=gbk";// 
                                                                              //request.Host = "search.yhd.com";

                    request.Headers.Add("Cookie", @"cna=eIRoHix2eSQBASQOA5B6Ls2Z; from=mobile.default; _m_h5_tk=d085629009e640f3e6990738cbdc96e1_1729660845593; _m_h5_tk_enc=ec54be99c9b6278ecaf7699d8c7cecfe; xlly_s=1; _samesite_flag_=true; cookie2=19040a608432afb9871377a391984293e; t=8c2bb4e8bbeb67186f69c73803ac19c5; _tb_token_=ee77aeae13ebd; sgcookie=E100sBnQ3%2FkkhuWb6sPctTb%2F01zaxBbftqnKEdb2ze2HQ%2BPQAmxyw9ccDo2VgQfSOpGxpCQ9OAB5aGrYwxkvt46b8%2Bq0mn9aKxdG7WUvnl9bEaE%3D; munb=2205181437154; unb=2205181437154; USERID=1946207929; SID=MTkwNDBhNjA4NDMyYWZiOTg3MTM3N2EzOTE5ODQyOTNl9OA1Of2k_idbxOQbnJ6_UA==; UTUSER=1946207929; isg=BOnp32ucqgDdcpa-3Dy8z4XN-JVDtt3oyhHsSIveZ1AUUg1k0Qa1uJ8AEPDkSnUg; tfstk=fbzmM0V65oofp3ROnz0fj6TsehjRHKgsCRLtBVHN4Yk7BnPNG1YiE8qx3SEYjNVaKsGOhPeobJF6DVHTSuTgO5aAGVCjlSgs79BdJPVbGVOaQoJcwQRzNXGNVs3phSgs79HioN74GJo46RSm7_0rsfLZ7AyZ4UlsUElwufJPZfMrQVkqg7Jr6j-2bxuwztCEhyU3zt68_MGIKnyjimDM8YTM51homvPqV9WgrFimLSkk79ZSXqMiFyWRq7w00-h7IwXo8kwuSDuGopG04W0rH2SHqqV8hy04-tYxw4MxYbzF6HM8rxeao05p-c3zJDu42g6xXqc3QrwDsFyUwWUjVPXHUAZxO4lg56-iIcSzg3-ek18spaV6fhiqNbDI_ZTRRXN27SClZHWS0bGPQ_fkfhiqNbDdZ_xFFmlSaO5..");

                    //request.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                    //request.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
                    //request.Headers.Add("Referer", "http://list.yhd.com/c0-0/b/a-s1-v0-p1-price-d0-f0-m1-rt0-pid-mid0-kiphone/");

                    //Encoding enc = Encoding.GetEncoding("GB2312"); // 如果是乱码就改成 utf-8 / GB2312

                    //如何自动读取cookie

                    //using (var writer = new StreamWriter(request.GetRequestStream()))
                    //{
                    //    writer.Write(Newtonsoft.Json.JsonConvert.SerializeObject(h5RequestModel));
                    //}

                    // Convert POST data to a byte array
                    byte[] byteArray = Encoding.UTF8.GetBytes(xo);

                    // Set the ContentLength property
                    request.ContentLength = byteArray.Length;

                    // Get the request stream
                    Stream dataStream = request.GetRequestStream();

                    // Write the data to the request stream
                    dataStream.Write(byteArray, 0, byteArray.Length);

                    // Close the Stream object
                    dataStream.Close();

                    request.CookieContainer = new CookieContainer();//1 给请求准备个container
                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)//发起请求
                    {
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                        }
                        else
                        {
                            try
                            {
                                //string sessionValue = response.Cookies["ASP.NET_SessionId"].Value;//2 读取cookie

                                StreamReader sr = new StreamReader(response.GetResponseStream());
                                html = sr.ReadToEnd();//读取数据
                                sr.Close();
                            }
                            catch (Exception ex)
                            {
                                html = null;
                            }
                        }
                    }
                }
            }
            catch (System.Net.WebException ex)
            {
                if (ex.Message.Equals("远程服务器返回错误: (306)。"))
                {
                    html = null;
                }
            }
            catch (Exception ex)
            {
                html = null;
            }
            return html;
        }

        //HttpClient--WebApi

        /// <summary>
        /// 下载html
        /// http://tool.sufeinet.com/HttpHelper.aspx
        /// HttpWebRequest功能比较丰富，WebClient使用比较简单
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string DownloadHtml(string url, Encoding encode)
        {
            string html = string.Empty;
            try
            {
                //https可以下载--
                //设置https等级
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) =>
                //{
                //    return true; //总是接受  
                //});
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                string xx = File.ReadAllText("text.json");
                HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;//模拟请求
                request.Timeout = 30 * 1000;//设置30s的超时
                request.Method = "GET";
                //设置用户请求的身份 设置的为浏览器

                //using (var writer = new StreamWriter(request.GetRequestStream()))
                //{
                //    writer.Write(xx);
                //}

                request.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1";
                //request.UserAgent = "User - Agent:Mozilla / 5.0(iPhone; CPU iPhone OS 7_1_2 like Mac OS X) App leWebKit/ 537.51.2(KHTML, like Gecko) Version / 7.0 Mobile / 11D257 Safari / 9537.53";

                request.ContentType = "text/plain;charset=UTF-8";// "text/html;charset=gbk";// 
                                                                 //request.Host = "search.yhd.com";

                //request.Headers.Add("Cookie", @"cna=eIRoHix2eSQBASQOA5B6Ls2Z; yunpk=1663868774470734; sca=71094501; atpsida=4e88d7902b0f5b692aeeb0ba_1729474976_3; cnaui=2205181437154;");

                //request.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                //request.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
                //request.Headers.Add("Referer", "http://list.yhd.com/c0-0/b/a-s1-v0-p1-price-d0-f0-m1-rt0-pid-mid0-kiphone/");

                //Encoding enc = Encoding.GetEncoding("GB2312"); // 如果是乱码就改成 utf-8 / GB2312

                //如何自动读取cookie
                request.CookieContainer = new CookieContainer();//1 给请求准备个container
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)//发起请求
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                    }
                    else
                    {
                        try
                        {
                            //string sessionValue = response.Cookies["ASP.NET_SessionId"].Value;//2 读取cookie

                            StreamReader sr = new StreamReader(response.GetResponseStream());
                            html = sr.ReadToEnd();//读取数据
                            sr.Close();
                        }
                        catch (Exception ex)
                        {
                            html = null;
                        }
                    }
                }
            }
            catch (System.Net.WebException ex)
            {
                if (ex.Message.Equals("远程服务器返回错误: (306)。"))
                {
                    html = null;
                }
            }
            catch (Exception ex)
            {
                html = null;
            }
            return html;
        }
    }
}
